package ua.yandex.threadpool;

import java.util.ArrayList;

public class MyFixedPool {

    private final int n;
    private final Thread[] array;
    private final ArrayList<Runnable> tasks;
    private volatile boolean flag;

    MyFixedPool(int number) {
        flag = true;
        n = number;
        array = new Thread[n];
        tasks = new ArrayList<>();
        MyRunnable r = new MyRunnable();
        for (int i = 0; i < n; i++) {
            array[i] = new Thread(r);
            array[i].start();
        }
    }

    public void close() throws InterruptedException {
        while (!tasks.isEmpty());
        flag = false;
        for (int i = 0; i < n; i++) {
            array[i].join();
        }
    }

    public synchronized void doThis(Runnable r) {
        tasks.add(r);
    }

    public class MyRunnable implements Runnable {

        @Override
        public void run() {
            while (flag) {
                while (tasks.isEmpty()) {
                    if (!flag) {
                        return;
                    }
                }
                synchronized (this) {
                    Runnable r = tasks.remove(tasks.size() - 1);
                    r.run();
                }
            }
        }

    }
}
